# -*- coding: utf-8 -*-

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api.urlfetch import fetch
import simplejson as json
import search_results_parser
import also_viewed_parser
import random
import sys
import moi_krug_user

def compact_json(obj):
  return json.dumps(obj, separators=(',',':'), ensure_ascii=False)
  
def DoFetch(url, decode=False):
  fetch_response = fetch(url).content
  if decode:
    fetch_response = fetch_response.decode('windows-1251')
  if u'<h1 class="subheader">Превышение лимита просмотров</h1>' in fetch_response:
    raise Exception("Limit exceeded")
  return fetch_response

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/html'
    self.response.out.write("<html><body><img src='/static/homepage.jpg'></body></html>")

class FetchImageByIdBase(webapp.RequestHandler):
  def get(self):
    id = self.request.get("id")
    fetch_response = DoFetch(self.url_to_fetch(id))
    self.response.headers["Content-Type"] = "image/jpeg"
    self.response.out.write(fetch_response)

class FetchPhoto(FetchImageByIdBase):
  def url_to_fetch(self, id):
    return "http://moikrug.ru/images/photo/%s.jpg" % id

class FetchPortrait(FetchImageByIdBase):
  def url_to_fetch(self, id):
    return "http://moikrug.ru/images/photo_portrait/%s.jpg" % id

class ParseUrlBase(webapp.RequestHandler):
  def get(self):
    url = self.request.get("url")
    fetch_response = DoFetch(url, True)
    self.response.headers["Content-type"] = 'text/javascript; charset="utf-8"'
    parsed = self.parse(fetch_response)
    for person in parsed["results"]:
      moi_krug_user.addOrUpdate(person["i"], person["n"], person["h"])
      del person["n"]
    self.response.out.write(compact_json(parsed))

class SearchResults(ParseUrlBase):
  def parse(self, content):
    return search_results_parser.parse(content)

class AlsoViewed(ParseUrlBase):
  def parse(self, content):
    return also_viewed_parser.parse(content)

class MoiKrugUser(webapp.RequestHandler):
  def get(self):
    id = int(self.request.get('id'))
    user = moi_krug_user.getByMoiKrugId(id)
    if user:
      user_dict = {"i": user.moi_krug_id,
                   "h": user.home_page,
                   "n": user.full_name}
    else:
      user_dict = {}
    self.response.headers["Content-type"] = 'text/javascript; charset="utf-8"'
    self.response.out.write(compact_json(user_dict))
    
class Proxy(webapp.RequestHandler):
  def get(self):
    url = self.request.get("url")
    fetch_response = fetch(url)
    self.response.headers["Content-type"] = "text/html"
    self.response.out.write(fetch_response.content)
    
class MoiKrugUsers(webapp.RequestHandler):
  def get(self):
    query = moi_krug_user.MoiKrugUser.all()
    users = []
    for user in query:
      users.append({"i": user.moi_krug_id,
                    "h": user.home_page,
                    "n": user.full_name})
    self.response.headers["Content-type"] = 'text/javascript; charset="utf-8"'
    self.response.out.write(compact_json(users))


application = webapp.WSGIApplication([('/', MainPage),
                                      ('/photo', FetchPhoto),
                                      ('/portrait', FetchPortrait),
                                      ('/search', SearchResults),
                                      ('/alsoviewed', AlsoViewed),
                                      ('/mkuser', MoiKrugUser),
                                      ('/content', Proxy),
                                      ('/mkusers', MoiKrugUsers)])

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
